package cs.oor;

import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class OrderRetrievalService extends Service {
    private DownloaderTask downloader;
    
    private class DownloaderTask extends AsyncTask<URL, Void, Boolean> {

        private class ShopAuthenticator extends Authenticator {
            protected PasswordAuthentication getPasswordAuthentication() {
                SharedPreferences settings = getSharedPreferences(Config.PREFS_NAME, 0);
                
                return new PasswordAuthentication(settings.getString(Config.SHOP_LOGIN, ""), settings.getString(Config.SHOP_PWD, "").toCharArray());
            }
        }

        protected Boolean doInBackground(URL... url) {
            
            
            Toast.makeText(getApplicationContext(), "URL Uebergebeen", Toast.LENGTH_LONG).show();
            URL path = url[0];
            String content = "";

            try {
                Authenticator.setDefault(new ShopAuthenticator());

                URLConnection conn = path.openConnection();
                conn.connect();

                content = conn.getContent().toString();
            } catch (IOException ex) {
                Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
                return false;
            }

            try {
                JSONObject json = new JSONObject(new JSONTokener(content));
                
                OrderStorage storage = new OrderStorage(getApplicationContext());
                
                storage.saveToDatabase(json);
            } catch (JSONException jex) {
                Toast.makeText(getApplicationContext(), jex.getMessage(), Toast.LENGTH_LONG).show();
                
                return false;
            }

            return true;
        }
    }

    
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(), intent.getData().toString(), Toast.LENGTH_LONG).show();

        
        Uri data = intent.getData();
        
        this.doBindService();
        try {
            this.downloader = new DownloaderTask();
            
            URL url = new URL(data.toString());
            
            URL[] urls = new URL[1];
            urls[0] = url;

            this.downloader.doInBackground(urls);
        } catch (MalformedURLException urlex) {
            Toast.makeText(getApplicationContext(), urlex.getMessage(), Toast.LENGTH_LONG).show();
        }
        return Service.START_FLAG_REDELIVERY;
    }
    
    public class LocalBinder extends Binder {
        OrderRetrievalService getService() {
            return OrderRetrievalService.this;
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    
    private final IBinder mBinder = new LocalBinder();

    protected Boolean isBound = false;

    private OrderRetrievalService retrievalService;

    protected ServiceConnection mConnection = new ServiceConnection() {
        
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            retrievalService = null;
            
            Toast.makeText(getApplicationContext(), "Service disconnected", Toast.LENGTH_LONG).show();
            
        }
        
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Service connected", Toast.LENGTH_LONG).show();
            retrievalService = ((OrderRetrievalService.LocalBinder)service).getService();
        }
    };
    
    void doBindService() {
        bindService(new Intent(getApplicationContext(), OrderRetrievalService.class), mConnection, Context.BIND_AUTO_CREATE);
        
        isBound = true;
    }
    
    void doUnbindService() {
        if (isBound) {
            unbindService(mConnection);
            isBound = false;
        }
    }
    
    public void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }
}
